package com.example.hello.service.impl;

import com.example.hello.mapper.UserMapper;
import com.example.hello.pojo.User;
import com.example.hello.service.RegistrationService;
import com.example.hello.service.SMSService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 用户注册业务逻辑实现
 */
@Service
public class RegistrationServiceImpl implements RegistrationService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SMSService smsService;

    // 用于密码加密（推荐使用 BCrypt）
    private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Override
    @Transactional  // 保证操作的原子性
    public boolean registerUser(String phone, String password, String smsCode) {
        // 先校验手机号是否已经注册
        User existingUser = userMapper.findByPhone(phone);
        if (existingUser != null) {
            return false;
        }

        // 验证短信验证码（包括有效期、是否匹配、是否未使用）
        boolean isValid = smsService.verifySMSCode(phone, smsCode);
        if (!isValid) {
            return false;
        }

        // 加密用户密码
        String encodedPassword = passwordEncoder.encode(password);

        // 构造新用户对象
        User newUser = new User();
        newUser.setPhone(phone);
        newUser.setPassword(encodedPassword);
        newUser.setStatus(1);  // 1 表示启用
        newUser.setRole(1);
        Date now = new Date();
        newUser.setCreatedAt(now);
        newUser.setUpdatedAt(now);
        newUser.setLastLoginAt(now);
        newUser.setNickname("可自定义昵称");
        newUser.setAvatar("");
        newUser.setGender(0);
        // birthday、locale、lastLoginIp 等字段可根据需要设置

        // 插入用户记录到数据库
        int rows = userMapper.insertUser(newUser);
        return rows > 0;
    }
}